package ar.com.spsolutions.splibrary.services;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.access.annotation.Secured;
import org.springframework.transaction.annotation.Transactional;

import ar.com.spsolutions.splibrary.book.LoanBook;
import ar.com.spsolutions.splibrary.general.IFindByNameService;
import ar.com.spsolutions.splibrary.general.RoleConverterService;
import ar.com.spsolutions.splibrary.repositories.UserRepository;
import ar.com.spsolutions.splibrary.user.User;

public class UserService extends TemplateEntityService<User> implements
		IFindByNameService<User> {

	private static final long serialVersionUID = -525804834755843013L;

	@Override
	@Transactional
	@Secured(value = { RoleConverterService.ROLE_USER })
	public void add(final User user) {
		new PasswordUtils().encript(user);
		super.add(user);
	}

	@Transactional(readOnly = true)
	public User findByName(final String name) {
		return this.getMyRepository().findByName(name);
	}

	private UserRepository getMyRepository() {
		return (UserRepository) this.getRepository();
	}

	@Override
	@Transactional(readOnly = true)
	public List<User> findByLikeName(final String name) {
		return this.getRepository().findByLike("name", name);
	}

	@Override
	public User get(final User user) {
		return this.getRepository().get(user);
	}

	@Transactional(readOnly = true)
	public List<LoanBook> getAllLoansFor(final User user) {
		return new ArrayList<LoanBook>(this.get(user).getLoans());
	}

	@Transactional(readOnly = true)
	public int sizeOfSearch(final String searchValue) {
		return this.getMyRepository().sizeOfSearch(searchValue);
	}

	@Transactional(readOnly = true)
	public List<? extends User> getResults(final String searchValue,
			final int first, final int count) {
		return this.getMyRepository().getResults(searchValue, first, count);
	}
}
